package com.ddyx.service.impl;

import java.util.Date;
import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.ConcurrentMap;

import org.apache.commons.lang3.time.DateUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import com.ddyx.service.IImageStorageService;
import com.qiniu.common.QiniuException;
import com.qiniu.common.Zone;
import com.qiniu.storage.Configuration;
import com.qiniu.storage.UploadManager;
import com.qiniu.util.Auth;

public class QiniuImageStorageService implements IImageStorageService {

	private static final Logger logger = LoggerFactory.getLogger(QiniuImageStorageService.class);
	
	private UploadManager uploadManager;
	private Auth auth;
	
	private String urlPrefix;
	
	private ConcurrentMap<String, Date> expiredTimeMap;
	private ConcurrentMap<String, String> uploadTokenMap;
	
	public QiniuImageStorageService(String accessKey, String secretKey, String urlPrefix) {
		this.urlPrefix = urlPrefix;
		Configuration cfg = new Configuration(Zone.zone1());
		uploadManager = new UploadManager(cfg);
		this.auth = Auth.create(accessKey, secretKey);
		this.expiredTimeMap = new ConcurrentHashMap<String, Date>(3);
		this.uploadTokenMap = new ConcurrentHashMap<String, String>(3);
	}
	
	private void validateUploadToken(String bucket) {
		Date now = new Date();
		//判断是否过期
		if(!expiredTimeMap.containsKey(bucket) || expiredTimeMap.get(bucket).before(now)) { 
			String uploadToken = auth.uploadToken(bucket);
			expiredTimeMap.put(bucket, DateUtils.addMinutes(now, 50));
			uploadTokenMap.put(bucket, uploadToken);
		}
	}
	
	@Override
	public String save(String bucket, String imagePath, byte[] imageData) {
		try {
			validateUploadToken(bucket);
			uploadManager.put(imageData, imagePath, uploadTokenMap.get(bucket));
			String domainName = urlPrefix.replaceAll("bucketname", bucket);
			return domainName + imagePath;
		} catch(QiniuException ex) {
			logger.error("上传图片错误：", ex);
		}
		return null;
	}

}
